package com.cup.bddm.api.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cup.bddm.api.entity.BranchEntity;
import com.cup.bddm.api.entity.MerchantEntity;
import com.cup.bddm.api.entity.StreetEntity;
import com.cup.bddm.api.mapper.BranchEntityMapper;
import com.cup.bddm.api.mapper.MerchantEntityMapper;
import com.cup.bddm.api.mapper.StreetEntityMapper;
import com.cup.bddm.api.req.SearchVo;
import com.cup.bddm.api.res.ResSearch;
import com.cup.bddm.api.res.ResVo;
import com.cup.bddm.api.service.MerchantService;
import com.cup.bddm.api.service.StreetService;
import com.cup.bddm.config.Config;
import com.cup.bddm.handler.Token;
import com.cup.bddm.util.StrUtil;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

@Controller
@RequestMapping("")
public class IndexController extends BaseController {
	@Autowired
	BranchEntityMapper branchEntityMapper;

	@Autowired
	StreetService streetService;

	@Autowired
	MerchantService merchantService;
	
	@Autowired
	StreetEntityMapper streetEntityMapper;
	
	@Autowired
	MerchantEntityMapper merchantEntityMapper;

	@RequestMapping("/")
	public String index() {
		return "index.html";
	}

	private static boolean stat = false;
	
	/**
	 * 搜索初始化（生成索引字段）
	 */
	@RequestMapping("/api/search_init")
	@ResponseBody
	public ResVo search_init() {
		if (stat) {
			ResVo.ok();
		}
		stat = true;
		int page = 1;
		while (page > 0) {
			List<StreetEntity> streets = streetEntityMapper.pageByPms(new HashMap<String, Object>(), new PageBounds(page, 1000, true));
			for (StreetEntity street : streets) {
				if (street.getStreet_nm_index() == null) {
					StreetEntity temp = new StreetEntity();
					temp.setId(street.getId());
					temp.setStreet_nm_index(StrUtil.indexEncode(street.getStreet_nm()));
					streetEntityMapper.updateById(temp);
				}
			}
			if (streets.size() > 0) {
				page++;
			} else {
				page = 0;
			}
		}
		page = 1;
		while (page > 0) {
			List<MerchantEntity> merchants = merchantEntityMapper.pageByPms(new HashMap<String, Object>(), new PageBounds(page, 1000, true));
			for (MerchantEntity merchant : merchants) {
				if (merchant.getStore_nm_index() == null) {
					MerchantEntity temp = new MerchantEntity();
					temp.setId(merchant.getId());
					temp.setStore_nm_index(StrUtil.indexEncode(merchant.getStore_nm()));
					merchantEntityMapper.updateById(temp);
				}
			}
			if (merchants.size() > 0) {
				page++;
			} else {
				page = 0;
			}
		}
		stat = false;
		return ResVo.ok();
	}

	/**
	 * 移动端搜索
	 */
	@Token
	@RequestMapping(value = "/api/search", method = RequestMethod.GET)
	@ResponseBody
	public ResVo mobileSearch(@RequestParam String wd) {
		String cup_branch_ins_cd = user().getCup_branch_ins_id_cd();
		if (Config.CUP_INS_ID.equals(cup_branch_ins_cd)) {
			cup_branch_ins_cd = null;
		}
		ResSearch res = new ResSearch();
		if (StringUtils.isEmpty(wd)) {
			return ResVo.data(res);
		}
		List<BranchEntity> branchs = branchEntityMapper.listByNm(wd);
		List<Map<String, Object>> list = new ArrayList<>();
		for (BranchEntity branch : branchs) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", "branch");
			map.put("id", branch.getId());
			map.put("name", branch.getCup_branch_nm());
			map.put("region", StrUtil.branchShotName(branch.getCup_branch_nm()));
			list.add(map);
		}
		res.setBranchs(list);
		wd = StrUtil.indexEncode(wd);
		List<StreetEntity> streets = streetService.matchByNm(cup_branch_ins_cd, wd);
		list = new ArrayList<>();
		for (StreetEntity street : streets) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", "branch");
			map.put("id", street.getId());
			map.put("name", street.getStreet_nm());
			map.put("region", StrUtil.branchShotName(street.getCup_branch_nm()));
			list.add(map);
		}
		res.setStreets(list);
		list = new ArrayList<>();
		List<MerchantEntity> merchants = merchantService.matchByNm(cup_branch_ins_cd, wd);
		for (MerchantEntity merchant : merchants) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", "branch");
			map.put("id", merchant.getId());
			map.put("name", merchant.getStore_nm());
			map.put("region", StrUtil.branchShotName(merchant.getCup_branch_nm()));
			list.add(map);
		}
		res.setMerchants(list);
		return ResVo.data(res);
	}

	/**
	 * PC端搜索
	 */
	@Token
	@RequestMapping(value = "/api/search", method = RequestMethod.POST)
	@ResponseBody
	public ResVo pcSearch(@RequestBody SearchVo vo) {
//		if (invalidToken(vo)) {
//			return the().token_err(token_err).vo();
//		}
//		if (vo.invalidIns()) {
//			return the().cup_branch_ins_id_cd().is_empty().vo();
//		}
		vo.resetVoIns(user());
		String nm = StrUtil.indexEncode(vo.getNm());
		List<Map<String, String>> results = new ArrayList<>();
		List<StreetEntity> streets = new ArrayList<>();
		List<MerchantEntity> merchants = new ArrayList<>();
		if (StringUtils.isEmpty(vo.getT()) || "1".equals(vo.getT())) {
			streets = streetService.matchByNm(vo.getCup_branch_ins_id_cd(), nm);
		}
		if (StringUtils.isEmpty(vo.getT()) || "2".equals(vo.getT())) {
			merchants = merchantService.matchByNm(vo.getCup_branch_ins_id_cd(), nm);
		}
		int i = 0;
		while (true) {
			if (streets.size() <= i && merchants.size() <= i) {
				break;
			}
			if (streets.size() > i) {
				StreetEntity street = streets.get(i);
				if (street != null) {
					Map<String, String> e = new HashMap<>();
					e.put("type", "street");
					e.put("code", street.getStreet_cd());
					e.put("name", street.getStreet_nm());
					e.put("addr", street.getStreet_addr());
					e.put("belong", street.getCity());
					results.add(e);
				}
			}
			if (merchants.size() > i) {
				MerchantEntity merchant = merchants.get(i);
				if (merchant != null) {
					Map<String, String> e = new HashMap<>();
					e.put("type", "merchant");
					e.put("code", merchant.getMchnt_cd());
					e.put("name", merchant.getStore_nm());
					e.put("addr", merchant.getStore_addr());
					e.put("belong", merchant.getStreet_cd());
					e.put("store_id", merchant.getStore_id());
					results.add(e);
				}
			}
			i++;
		}
		return ResVo.data(results);
	}
	
}
